import { getControlDataActivityInfoTimeData } from '@/store/index-utils'
import { getCompIdByParam, isHasOwnProperty } from '@/plugins/utils'
import { GENERAL_TYPES_MAP } from '@/common/const-general'
import { CONTROL_TYPES } from '@/common/const-wb'
import axios_ from '@/utils/axios'
import { getQueryString, isJSON, isWeibo } from '@/plugins/utils'

export const ERROR_CODES = [900121]

function changePageOrPopId(activityInfo, attrs) {
  if(activityInfo.isLoad && activityInfo.isHave && activityInfo.isJoin) {
    if(activityInfo.jumpPopId) {
      attrs.popId = activityInfo.jumpPopId;
    }
    if(activityInfo.jumpPageId) {
      attrs.pageId = activityInfo.jumpPageId;
    }
  }
}

// 900121: '数据不存在'

const state = {
}
const actions = {
  async getSiteActivityData({commit, rootState}, siteData){
    // 获取活动信息参数
    let {controlData, activityInfo, timeData} = getControlDataActivityInfoTimeData(siteData, rootState.componentMap)

    if(timeData){
      const serverTimeData =  await axios_.post('/feinit/timer', { site_id: siteData.id, com_id: timeData.compId, action: 'get' })

        let time = new Date().toLocaleDateString()
        if(serverTimeData.data.data.end){
          time = serverTimeData.data.data.end
        }
        rootState.timeObj.timerTime = siteData.controls[timeData.compId][CONTROL_TYPES.timer].data.time = time
        rootState.timeObj.serverTime = serverTimeData.data.data.current
    }

    if(controlData){
      _.merge(activityInfo, siteData.activityInfo)
      let compId = activityInfo.compId
      let url = '';
      let params = { site_id: siteData.id, com_id: compId };
      let activityType = controlData.data.activityType;

      if(activityType == GENERAL_TYPES_MAP.scoreForm) {
        const relateCompId = getCompIdByParam(activityInfo.relateCompId)
        if(relateCompId) {
          params.com_id = relateCompId
        }
        ///feinit/formlatest?site_id=1580&com_id=6&uid=  表单获取自己最新的一条数据, 增加uid参数, 不加uid就是获取自己的
        url = '/feinit/formlatest';
        const uid = getQueryString("uid")
        if(uid && uid.length > 0) {
          params.uid = uid
        }
      }else if(activityType == GENERAL_TYPES_MAP.lotteryForm){
        url = '/feinit/Lottery_luckyform'
        const relateCompId = getCompIdByParam(activityInfo.relateCompId) || activityInfo.relateCompId;
        params.com_id = relateCompId;
      }else if(activityType == GENERAL_TYPES_MAP.baoming){
        url = '/feinit/general'
        const relateCompId = getCompIdByParam(activityInfo.relateCompId) || activityInfo.relateCompId;
        params.com_id = relateCompId;
        params.ele_key = activityType;
      }else{
        url = '/feinit/general';
        params.ele_key = activityType;
      }

      const activityInfoData =  await axios_.post(url,params)
      //营销峰会抽奖
      if(activityType == GENERAL_TYPES_MAP.activity) {
        // activityInfoData.data.data.ext_1 = 0 是数组表示没有参加
        if(rootState.timerTime && rootState.timerTime.length > 0){
          rootState.timeObj.isTimerStart = true
          let now = (new Date(rootState.timeObj.serverTime.replace(/-/g,  "/"))).valueOf();
          let end = (new Date(rootState.timeObj.timerTime.replace(/-/g,  "/"))).valueOf();
          if(end - now <= 0){
            rootState.timeObj.isTimerEnd = true
          }
        }
        let isFirstPage = (_.isArray(activityInfoData.data.data) || activityInfoData.data.data.ext_1 == -2) && !rootState.timeObj.isTimerEnd && rootState.timeObj.isTimerStart
        if(isFirstPage || !rootState.isTimerEnd && !rootState.timeObj.isTimerStart){
          activityInfo.isJoin = false
        }else{
          //有数据的时候就显示第二页
          activityInfo.isJoin = true
        }

        changePageOrPopId(activityInfo, siteData.attrs)
        commit('setPageData', siteData, {root:true})
        commit('updateActivityInfo', { data: activityInfo}, {root:true})

        commit('updateInitGeneral', {id: compId, controlId: controlData.controlId, data: activityInfoData.data.data}, {root:true})
      }else if(activityType == GENERAL_TYPES_MAP.lotteryForm) {
        // 抽奖 / 表单提交： 是否中奖 / 是否提交表单；跳转页面 636 新年求稳签
        // 获取 data
        // 获取活动信息需要的关联组件id
        let lotteryData = activityInfoData && activityInfoData.data && activityInfoData.data.data;

        const bIsFormed = lotteryData && !isNaN(parseInt(lotteryData.num_form)) && parseInt(lotteryData.num_form) > 0;
        const bIsLucked = lotteryData && !isNaN(parseInt(lotteryData.num_luck)) && parseInt(lotteryData.num_luck) > 0;
        // debug info
        // activityInfo.isLoad = true
        // bIsLucked = true

        //如果是load那么页面一进来就弹出表单填写信息页面，否则就是在按钮触发的时候弹出表单页面
        if(activityInfo.isLoad){
          // 是否中奖
          if(bIsLucked) {
            // 是否提交表单
            if(bIsFormed) {
              // continue;
              // commit('updatePageIndex', 0);
            }else {
              if(activityInfo.jumpPopId){
                siteData.attrs.popId = activityInfo.jumpPopId;
              }
              if(activityInfo.jumpPageId) {
                siteData.attrs.pageId = activityInfo.jumpPageId;
              }
            }
          }
        }
        changePageOrPopId(activityInfo, siteData.attrs)
        commit('setPageData', siteData, {root:true});
        commit('updateActivityInfo', { data: lotteryData}, {root:true})
        if(!activityInfo.isLoad){
          commit('updateLotteryForm', {id: compId, controlId: controlData.controlId, data: {isPopup: bIsLucked && !bIsFormed}}, {root:true});
        }
      }else if(activityType == GENERAL_TYPES_MAP.scoreForm) {
        //{自己的uid:{},url传的uid:{}}
        //character: "ISFP-峡谷梦旅人"level: "星耀"platform: "安卓"purpose: "CPDD"sex: "女"skills: "射手"
        const userDatas = activityInfoData.data.data
        const uid = getQueryString("uid")
        const uidKey = uid ? uid : siteData.uid
        const userData = userDatas[uidKey]
        const selfUserData = userDatas[siteData.uid]
        const relateCompId = getCompIdByParam(activityInfo.relateCompId)
        
        if(activityInfoData.data.code == 0) {
          if(!_.isArray(selfUserData)) {
            activityInfo.isJoin = true
          } else {
            activityInfo.isJoin = false
          } 
        }else{
          activityInfo.isJoin = false
        }
        let iconUrls
        if(activityInfo.params && isJSON(activityInfo.params)) {
          const activityInfoParams = JSON.parse(activityInfo.params)
          iconUrls = activityInfoParams.sexIconUrl.split(',')
          commit('updateBindData', { key: 'sexIconUrls', value: iconUrls }, {root:true})
        }
        if(!_.isArray(userData) && userData && siteData.uid) {
          if(userData.sex == "男") {
            userData.sexIconUrl = iconUrls[0]
          } else {
            userData.sexIconUrl = iconUrls[1]
          }
        }
        // changePageOrPopId(activityInfo, siteData.attrs)
        //{"uid":{"pageId":1,"jumpPageId":3}}
        if(activityInfo.params && isJSON(activityInfo.params) && siteData.uid) {
          const activityInfoParams = JSON.parse(activityInfo.params)
          if(isHasOwnProperty(activityInfoParams, 'uid')) {
            const jumpObj = activityInfoParams.uid
            const uidUserData = userDatas[uid]
            const selfUserData = userDatas[siteData.uid]
            // url 上带 uid 
            if(uid) {
              //有uid 被 标记 看用户自身是否参加过活动与是否被标记
              if(uidUserData.del == -1) {
                if(_.isArray(selfUserData)) {
                  //没有参与过的用户
                  //默认页面 不做跳转 首页 点击按钮跳转填写表单页面
                } else {
                  //跳转 首页 点击按钮跳转列表页 新增一个首页 只跳转列表页
                  siteData.attrs.pageId = jumpObj.markedJumpPageId
                }
              } else {
                if(_.isArray(selfUserData)) {
                  //没有参与过的用户 跳转漂流瓶页面 跳转 表单填写页面
                  if(jumpObj.pageId) {
                    siteData.attrs.pageId = jumpObj.pageId
                  }
                } else {
                  //跳转漂流瓶页面 跳转 列表页 
                  if(jumpObj.jumpPageId) {
                    siteData.attrs.pageId = jumpObj.jumpPageId
                  }
                }
              }
            } else {
              if(_.isArray(selfUserData)) {
                //没有参与过的用户
                //默认页面 不做跳转 首页 点击按钮跳转填写表单页面
              } else {
                //直接跳转列表页 
                siteData.attrs.pageId = activityInfo.jumpPageId
              }
            }
          }
        }
        
        commit('setPageData', siteData, {root:true})
        _.merge(activityInfo, userData)
        commit('updateActivityInfo', { id: compId, controlId: controlData.controlId ,data: activityInfo}, {root:true})
        if(activityInfoData.data.code == 0) {
          commit('updateFormValue', {id: relateCompId || compId, scoreData: userData}, {root:true});
          commit("updateEndSelectScoreFormValues", userData, {root:true});
        }
      }else if(activityType == GENERAL_TYPES_MAP.tree || activityType == GENERAL_TYPES_MAP.randbm){
        //参与后 跳转页面  activityInfo 里有 jumpPageId信息
        if(activityInfoData.data.data.hasOwnProperty("isattend")) {
          activityInfo.isJoin = activityInfoData.data.data.isattend;
        }else{
          activityInfo.isJoin = activityInfoData.data.data;
        }
        _.merge(activityInfo, activityInfoData.data.data);
        changePageOrPopId(activityInfo, siteData.attrs)
        commit('updateActivityInfo', { data: activityInfo}, {root:true})
        commit('setPageData', siteData, {root:true})
      }else if(activityType == GENERAL_TYPES_MAP.baoming) {
        let ext_1 = activityInfoData.data.data.ext_1
        if(ext_1 && ext_1.length> 0){
          activityInfo.isJoin = true
          siteData.attrs.pageId = activityInfo.jumpPageId
        }else{
          activityInfo.isJoin = false
        }
        _.merge(activityInfo, activityInfoData.data.data)
        changePageOrPopId(activityInfo, siteData.attrs)
        commit('updateActivityInfo', { data: activityInfo}, {root:true})
        commit('setPageData', siteData, {root:true})
      }
    }
  },
}
const mutations = {
}
const getters = {
}


export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
